<?php
namespace Manage\Controller;
use Common\Controller\ManageBaseController;
use Common\Model\ConfigModel;


class ConfigController extends ManageBaseController{
	
	/**
	 * @param number $status	状态
	 */
	public function lists($ajax=null,$status=null,$page=null,$rows=null) {
		$map = array(); $status_view = array('default'=>'所有','del'=>'已删除','forbid'=>'禁用','allow'=>'正常');
		//查询条件 处理
		$now_status = $status_view['default'];
		if (isset($status) && key_exists($status, ConfigModel::$mystat)) { //指定查询状态
			$map['status'] = ConfigModel::$mystat[$status];
			$now_status = $status_view[$status];
		}else {
			$map['status'] = array('EGT',0); //默认查询状态为未删除的数据
		}
		if ($page <= 0) {
			$page = 1;
		}
		if ($rows > 0) {
			$listRows = $rows;
		}else {
			$listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
		}
		//筛选条件
		$filter = I('param.');
		if ($filter['keyword']) {
			$map['_string'] = "(`title` like '%".$filter['keyword']."%') OR (`name` like '%".$filter['keyword']."%')";
			$this->assign('keyword', $filter['keyword']);
		}
		/******************/
		if ($ajax==='y') {
			$model = new ConfigModel();
			$total = $model->where($map)->count(); //总记录数
			$list = $model->where($map)->page("$page,$listRows")->select();
				
			//list格式处理
			
			foreach ($list as &$v) {
				$v['type_f'] = ConfigModel::$type[$v['type']];
				$v['updatetime_f'] = date('Y-m-d H:i:s',$v['update_time']);
			}
			unset($v);
			
			$list = array("total"=>(int)$total,"rows"=>$list);
			$this->ajaxReturn($list);
		}else {
			$this->assign('_page', $page);
			$this->assign('_rows', $listRows);
			$this->assign('now_status',$now_status); //当前页面筛选的状态
				
			// 记录当前列表页的cookie
			cookie(C('CURRENT_URL_NAME'),$_SERVER['REQUEST_URI']);
				
			$this->display();
		}
	}
	
	public function delete($id) {
		$return = array('status'=>0,'info'=>'');
		$model = new ConfigModel();
		$model->where('id='.$id)->setField('status','-1');
		$return['status']=1;
		$return['info']='删除成功';
		$this->ajaxReturn($return);
	}
	
	public function update() {
		$return = array('status'=>0,'info'=>'');
		$data = I('post.');
		if ($data['id']<=0) {
			$return['info']='请先选择要更新的记录';
			$this->ajaxReturn($return);
		}
		$model = new ConfigModel();
		if (false !== $model->create($data)) {
			if (false !== $model->save()) {
				$model->clearCache();//清除缓存
				$return['status']=1;
				$return['info']='更新成功';
				$this->ajaxReturn($return);
			}
		}
		$return['info']=$model->getError();
		$this->ajaxReturn($return);
	}
	
	public function insert() {
		$return = array('status'=>0,'info'=>'');
		$data = I('post.');
		$model = new ConfigModel();
		if (false !== $model->create($data)) {
			if (false !== $model->add()) {
				$model->clearCache();//清除缓存
				$return['status']=1;
				$return['info']='新建成功';
				$this->ajaxReturn($return);
			}
		}
		$return['info']=$model->getError();
		$this->ajaxReturn($return);
	}
}